package com.xingkeduo.util.pojo.domain;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.xingkeduo.util.pojo.base.BaseJson;
import com.xingkeduo.util.pojo.exception.InputParamException;
import com.xingkeduo.util.tool.RegularUtil;

/**
 * 分页转换类
 * 
 * @author GJ
 * @time 2019年2月21日 上午10:54:05
 * @description
 */
public class PageJTO extends BaseJson {
	public static Page<?> createFromJson(String json, int pageSize) throws Throwable {
		JsonNode root = MAPPER.readTree(json);
		if (!root.isObject())
			throw new InputParamException(InputParamException.Type.INVALID, "参数格式");

		JsonNode pageJson = validPage(root);

		Page<?> page = new Page<>();
		page.setPageNo(validIndex(pageJson));
		page.setPageSize(validSize(pageJson, pageSize));

		return page;
	}

	public static ObjectNode toJson(Page<?> page, ArrayNode on) throws Throwable {
		ObjectNode root = MAPPER.createObjectNode();

		root.put("page_index", page.getPageNo());
		root.put("page_total", page.getPageTotal());
		root.put("record_total", page.getRecordTotal());
		root.putPOJO("rows", on);

		return root;
	}

	protected static JsonNode validPage(JsonNode node) throws Throwable {
		String key = "page";
		if (!node.has(key))
			throw new InputParamException(InputParamException.Type.NULL, key);

		JsonNode value = node.path(key);
		if (!value.isObject())
			throw new InputParamException(InputParamException.Type.INVALID, key);

		return value;
	}

	protected static int validIndex(JsonNode node) throws Throwable {
		String key = "index";
		if (!node.has(key))
			throw new InputParamException(InputParamException.Type.NULL, key);

		String value = node.path(key).asText().trim();
		if (!RegularUtil.isPositiveInteger(value))
			throw new InputParamException(InputParamException.Type.INVALID, key);
		return Integer.parseInt(value);
	}

	protected static int validSize(JsonNode node, int pageSize) throws Throwable {
		String key = "size";
		if (node.has(key)) {
			String value = node.path(key).asText().trim();
			if (!RegularUtil.isPositiveInteger(value))
				throw new InputParamException(InputParamException.Type.INVALID, key);
			return Integer.parseInt(value);
		}
		return pageSize;
	}
}
